need to Need to call the Microsoft GraphApi from the .net application and get the user details based on the email address

pk 5 Reputation points
2024-05-07T20:13:50.26+00:00

Hi,

I have a below requirement.

I need to call the microsoft GraphApi from the .net application and get the user details based on the email address he/she types in the textbox.

In Azure portal - i have enabled (Any Microsoft Entra ID tenant - Multitenant) option. i.e anyone from their personal Microsoft accounts can access the application.

Note: I need to access the users not only in organizational directory but i need fetch details about the personal Microsoft accounts.

For eg: lets assume i have addded 1 user (abc@yahoo.com) and given (User.Read & User.Read.All) permission has been provided.

when i tried to access it from my .net application using graph api. it is working perfectly.

But my requirement is i pass personal microsoft email address (eg: abc@aol.com) also, it should work. But currently its not working with personal microsoft email address.

Please help me with the same. Below is my code:

var app = ConfidentialClientApplicationBuilder

 .Create(ConfigurationManager.AppSettings["ida:ClientId"])

 .WithClientSecret("youClientSecret") //replace with your client secret

 .WithAuthority(new Uri(ConfigurationManager.AppSettings["ida:Instance"] + ConfigurationManager.AppSettings["ida:TenantId"]))

 .Build();
```var result = await app.AcquireTokenForClient(new[] { "https://graph.microsoft.com/.default" }).ExecuteAsync();

var token = result.AccessToken;

//userEmail = "abc@yahoo.com";

 userEmail = "abc@aol.com";

string graphApiUrl = $"https://graph.microsoft.com/v1.0/users?$filter=mail eq '{userEmail}'&$select=id,displayName,userPrincipalName,signInType";

using (var client = new HttpClient())

{

```go
string accessToken = token;

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

HttpResponseMessage response = await client.GetAsync(graphApiUrl);

if (response.IsSuccessStatusCode)

{

    string content = await response.Content.ReadAsStringAsync();

    // Parse the JSON response to get the signInType property

    // For example, using Newtonsoft.Json:

    dynamic users = Newtonsoft.Json.JsonConvert.DeserializeObject(content);

    foreach (var user in users.value)

    {

        string signInType = user.signInType;

        if (signInType == "microsoftAccount")

        {

            Console.WriteLine("User is linked to a Microsoft account.");

        }

        else

        {

            Console.WriteLine("User is not linked to a Microsoft account.");

        }

    }

}

else

{

    Console.WriteLine($"Failed to call the API. Status code: {response.StatusCode}");

}
```}

 



Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,873 questions
{count} votes